package com.yunxi.module.infra.service.logger.impl;

import com.yunxi.framework.common.util.object.BeanUtils;
import com.yunxi.module.infra.dto.logger.ApiAccessLogCreateReqDTO;
import com.yunxi.module.infra.mapper.logger.ApiAccessLogMapper;
import com.yunxi.module.infra.model.logger.ApiAccessLogDO;
import com.yunxi.module.infra.service.logger.ApiAccessLogService;
import groovy.util.logging.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * <p>
 * API 访问日志 Service 接口实现类
 * </p>
 *
 * @author lidy
 * @since 2024-05-17
 */
@Slf4j
@Validated
@Service
public class ApiAccessLogServiceImpl implements ApiAccessLogService {

    @Resource
    private ApiAccessLogMapper apiAccessLogMapper;

    /**
     * 创建 API 访问日志
     *
     * @param reqDTO API 访问日志
     */
    @Override
    public void createApiAccessLog(ApiAccessLogCreateReqDTO reqDTO) {
        ApiAccessLogDO apiAccessLogDO = BeanUtils.toBean(reqDTO, ApiAccessLogDO.class);
        apiAccessLogMapper.insert(apiAccessLogDO);
    }

    /**
     * 清理 exceedDay 天前的访问日志
     *
     * @param exceedDay   超过多少天就进行清理
     * @param deleteLimit 清理的间隔条数
     * @return 结果
     */
    @Override
    @SuppressWarnings("DuplicatedCode")
    public Integer cleanAccessLog(Integer exceedDay, Integer deleteLimit) {
        int count = 0;
        LocalDateTime expireDate = LocalDateTime.now().minusDays(exceedDay);
        // 循环删除，直到没有满足条件的数据
        for (int i = 0; i < Short.MAX_VALUE; i++) {
            int deleteCount = apiAccessLogMapper.deleteByCreateTimeLt(expireDate, deleteLimit);
            count += deleteCount;
            // 达到删除预期条数，说明到底了
            if (deleteCount < deleteLimit) {
                break;
            }
        }
        return count;
    }
}
